﻿Imports Business
Imports Entities
Imports DataAccess

Public Class RealizarVenta
    Private _Cliente As New clientes
    Private _Calle As New calles
    Private _Villa As New villas
    Private _Chofer As New choferes
    Private _FPago As New formapagos
    Private _Camion As New camiones
    Private _Item_ As New itemes

    Private _ChoferesList As New List(Of choferes)
    Private _CallesList As New List(Of calles)
    Private _ClientesList As New List(Of clientes)
    Private _VillasList As New List(Of villas)
    Private _FPagoList As New List(Of formapagos)
    Private _CamionesList As New List(Of camiones)
    Private _GarantiasList As New List(Of garantias)
    Private _ItemesList As New List(Of itemes)

    Private Sub RealizarVenta_Activated(sender As Object, e As EventArgs) Handles Me.Activated

        Limpiar()

        TituloCombos()
        TituloDisponibles()
        TituloGarantias()
        TituloVenta()
    End Sub


#Region "Métodos Publicos"
    Public Sub UpdateCallesList(ByVal zVillaId As Decimal)
        cVillas.SelectedValue = zVillaId
        If IsNumeric(cVillas.SelectedValue) AndAlso cVillas.SelectedValue > -1 Then
            _CallesList = CalleBL.ListByVillaId(cVillas.SelectedValue)
            TituloCalle()
        End If
    End Sub
    Public Sub UpdateVillasList()
        _VillasList = VillaBL.List
        TituloCombos()
    End Sub
#End Region

#Region "Métodos Privados"
    Private Sub CargarListas()
        _ChoferesList = ChoferBL.List
        _VillasList = VillaBL.List
        _FPagoList = FormaPagoBL.List
        _CamionesList = CamionBL.List
        _GarantiasList = GarantiaBL.List
        _ItemesList = ItemBL.List

    End Sub

    Private Sub Limpiar()
        CargarListas()
        TituloCombos()
        TituloDisponibles()
        TituloGarantias()
        TituloVenta()

        cCamion.SelectedIndex = -1
        cChofer.SelectedIndex = -1
        cFormaPago.SelectedIndex = -1
        tNumero.Clear()
        tRut.Clear()
        tNombre.Clear()
        tFono.Clear()
        gVenta.Rows.Clear()

        LimpiarTotales()
       
        xComentarios.Clear()
        lbClienteNuevo.Visible = False
        oGPendiente.Checked = False
        oGPendiente.Enabled = False
        tFechaDevolucion.Value = Now
        tFechaPago.Value = Now
       
        oPedidoPOS.Checked = False
        tNPedido.Clear()
       
    End Sub
    Private Sub LimpiarTotales()
        tMontoTotal.Text = FormatCurrency(0)
        tSubTotal.Text = FormatCurrency(0)
        tKilos.Text = FormatNumber(0)
        tMontoCliente.Text = FormatCurrency(0)
        tPendiente.Text = FormatCurrency(0)
        tDesctoPOS.Text = FormatCurrency(0)
        tDescto.Text = FormatCurrency(0)
    End Sub
    Private Sub TituloCombos()
        With cFormaPago
            .DataSource = _FPagoList
            .ValueMember = "FORMAPAGO"
            .DisplayMember = "DESCRIPCION"
        End With

        With cChofer
            .DataSource = _ChoferesList
            .ValueMember = "RUT"
            .DisplayMember = "NOMBRES"
        End With

        With cVillas
            .DataSource = _VillasList
            .ValueMember = "VILLA"
            .DisplayMember = "NOMBRE"
        End With

        With cCamion
            .DataSource = _CamionesList
            .ValueMember = "PATENTE"
            .DisplayMember = "DESCRIPCION"
        End With
    End Sub

    Private Sub TituloDisponibles()
        gDisponibles.DataSource = _ItemesList
        gDisponibles.Font = New Drawing.Font("Tahoma", 10, FontStyle.Regular, GraphicsUnit.Point)

        gDisponibles.Columns("ITEM").Visible = False
        gDisponibles.Columns("PROVEEDOR").Visible = False
        gDisponibles.Columns("GARANTIA").Visible = False
        gDisponibles.Columns("CANTIDADKILOS").Visible = False
        gDisponibles.Columns("PRECIOVENTA").Visible = False
        gDisponibles.Columns("ACTIVO").Visible = False
        gDisponibles.Columns("DESCRIPCION").HeaderText = "Descripción"
        gDisponibles.Columns("DESCRIPCION").Width = 250

        gDisponibles.Columns("STOCK").HeaderText = "Stock"
        gDisponibles.Columns("STOCK").Width = 100
    End Sub

    Private Sub TituloGarantias()
        gGarantias.DataSource = _GarantiasList
        gGarantias.Font = New Drawing.Font("Tahoma", 10, FontStyle.Regular, GraphicsUnit.Point)

        gGarantias.Columns("GARANTIA").Visible = False
        gGarantias.Columns("CAPACIDAD").Visible = False
        gGarantias.Columns("PRECIOVENTA").Visible = False

        gGarantias.Columns("ACTIVO").Visible = False

        gGarantias.Columns("STOCK").HeaderText = "Stock"
        gGarantias.Columns("STOCK").Width = 50

        gGarantias.Columns("DESCRIPCION").HeaderText = "Descripción"
        gGarantias.Columns("DESCRIPCION").Width = 250


    End Sub

    Private Sub AjustarColumnas()
        For Each col As DataGridViewColumn In gVenta.Columns
            col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        Next
    End Sub

    Private Sub TituloVenta()

        'Dim ComboBoxCell As DataGridViewCell = New DataGridViewComboBoxCell
        'Dim TextBoxCell As DataGridViewCell = New DataGridViewTextBoxCell
        'Dim ButtonCell As DataGridViewCell = New DataGridViewButtonCell

        'Dim ColumnaGarantiaCliente As New DataGridViewComboBoxColumn

        'With ColumnaGarantiaCliente
        '    .HeaderText = "Garantía Cliente"
        '    .Name = "GARANTIACLIENTE"
        '    .ReadOnly = False
        '    .ValueType = Type.GetType("System.Int64")
        '    .Visible = True
        '    .Width = 150
        '    .Resizable = False
        '    .CellTemplate = ComboBoxCell
        '    .DataSource = _GarantiasList
        '    .DisplayMember = "DESCRIPCION"
        '    .ValueMember = "GARANTIA"
        'End With

        ''Dim ColumnaVenta As New DataGridViewColumn With {.HeaderText = "Venta",
        ''                                           .Name = "VENTA",
        ''                                           .ReadOnly = True,
        ''                                           .ValueType = Type.GetType("System.Int64"),
        ''                                           .Visible = False,
        ''                                           .Width = 20,
        ''                                           .Resizable = False,
        ''                                            .CellTemplate = plantilla}
        'Dim ColumnaDescripcion As New DataGridViewColumn With {.HeaderText = "Descripción",
        '                                          .Name = "DESCRIPCION",
        '                                          .ReadOnly = True,
        '                                          .ValueType = Type.GetType("System.String"),
        '                                          .Visible = True,
        '                                          .Width = 180,
        '                                          .Resizable = True,
        '                                          .CellTemplate = TextBoxCell
        '                                                      }
        'Dim ColumnaItem As New DataGridViewColumn With {.HeaderText = "Item",
        '                                           .Name = "Item",
        '                                           .ReadOnly = True,
        '                                           .ValueType = Type.GetType("System.Int64"),
        '                                           .Visible = False,
        '                                           .Width = 20,
        '                                           .Resizable = False,
        '                                          .CellTemplate = TextBoxCell}

        'Dim ColumnaGarantia As New DataGridViewColumn With {.HeaderText = "Cantidad",
        '                                          .Name = "GARANTIA",
        '                                          .ReadOnly = True,
        '                                          .ValueType = Type.GetType("System.Int64"),
        '                                          .Visible = True,
        '                                          .Width = 50,
        '                                          .Resizable = False,
        '                                          .CellTemplate = TextBoxCell}
        'Dim ColumnaPrecioVenta As New DataGridViewColumn With {.HeaderText = "Precio de Venta",
        '                                          .Name = "PRECIOVENTA",
        '                                          .ReadOnly = False,
        '                                          .ValueType = Type.GetType("System.Int64"),
        '                                          .Visible = True,
        '                                          .Width = 100,
        '                                          .Resizable = False,
        '                                          .CellTemplate = TextBoxCell}
        'Dim ColumnaEliminar As New DataGridViewButtonColumn With {.HeaderText = "Quitar",
        '                                          .Name = "QUITAR",
        '                                          .ReadOnly = False,
        '                                          .ValueType = Type.GetType("System.Int64"),
        '                                          .Visible = True,
        '                                          .Width = 50,
        '                                          .Resizable = False,
        '                                                  .CellTemplate = ButtonCell,
        '                                                          .Text = "Quitar"}
        'If Not gVenta.Columns.Contains(ColumnaItem) Then
        '    gVenta.Columns.Add(ColumnaItem)
        'End If
        'If Not gVenta.Columns.Contains(ColumnaGarantia) Then
        '    gVenta.Columns.Add(ColumnaGarantia)
        'End If

        'If Not gVenta.Columns.Contains(ColumnaDescripcion) Then
        '    gVenta.Columns.Add(ColumnaDescripcion)
        'End If
        'If Not gVenta.Columns.Contains(ColumnaPrecioVenta) Then
        '    gVenta.Columns.Add(ColumnaPrecioVenta)
        'End If
        'If Not gVenta.Columns.Contains(ColumnaGarantiaCliente) Then
        '    gVenta.Columns.Add(ColumnaGarantiaCliente)
        'End If
        'If Not gVenta.Columns.Contains(ColumnaEliminar) Then
        '    gVenta.Columns.Add(ColumnaEliminar)
        'End If



        gVenta.RowHeadersVisible = False
        gVenta.Font = New Drawing.Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point)
        gVenta.Columns("PRECIOVENTA").DefaultCellStyle.Format = "$ ###,##0"
        gVenta.Columns("PRECIOVENTA").HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomRight
        'gVenta.Columns("PRECIOVENTA").Width = 90
        'gVenta.Columns("DESCRIPCION").Width = 170
        AjustarColumnas()
        gVenta.Columns("DESCRIPCION").ReadOnly = True

        gVenta.Columns("ITEM").Visible = False

        gVenta.Columns("GARANTIA").Visible = False
        gVenta.Columns("DESCRIPCION").DisplayIndex = 0
        gVenta.Columns("PRECIOVENTA").DisplayIndex = 1
        gVenta.Columns("GARANTIACLIENTE").DisplayIndex = 2
        gVenta.Columns("QUITAR").DisplayIndex = 3


    End Sub

    Private Sub TituloCalle()
        If Not IsNothing(_CallesList) AndAlso _CallesList.Count > 0 Then
            With lsCalles
                .DataSource = _CallesList
                .ValueMember = "CALLE"
                .DisplayMember = "NOMBRE"
            End With
        Else
            tCalle.Clear()
            lsCalles.DataSource = Nothing
        End If
    End Sub

    Private Sub CalcularTotales()

        Dim total, kilos As Integer
        For Each fila As DataGridViewRow In gVenta.Rows
            total += fila.Cells("PRECIOVENTA").Value
            If fila.Cells("ITEM").Value > 0 Then
                kilos += ItemBL.GetKilos(fila.Cells("ITEM").Value)
            End If
        Next
        tKilos.Text = FormatNumber(kilos)
        If total = 0 Then
            LimpiarTotales()
        End If
        tSubTotal.Text = FormatCurrency(total)
        If cFormaPago.Text.Contains("VALE") Then
            tMontoTotal.Text = FormatCurrency(0)
            tMontoCliente.Text = FormatCurrency(0)
            tFechaPago.Visible = False
            tPendiente.Text = FormatCurrency(0)
            tDescto.Text = FormatCurrency(0)
            tDesctoPOS.Text = FormatCurrency(0)
            ' tSubTotal.Text = FormatCurrency(0)
        Else
            tMontoTotal.Text = FormatCurrency(total - FormatNumber(CLng((tDescto.Text))) - FormatNumber(CLng((tDesctoPOS.Text))))
            ' tMontoCliente.Text = FormatCurrency(tMontoTotal.Text)
            CalcularPendiente()

            If CLng(tMontoCliente.Text) < CLng(tMontoTotal.Text) Then
                'tMontoCliente.Text = FormatCurrency(tMontoTotal.Text)
                tMontoCliente.Text = FormatCurrency(FormatNumber(tMontoTotal.Text) - FormatNumber(CLng((tPendiente.Text))))
            Else
                'tMontoCliente.Text = FormatCurrency(tMontoTotal.Text)
                tMontoCliente.Text = FormatCurrency(FormatNumber(tMontoTotal.Text))
            End If
        End If
    End Sub

    Private Sub CalcularPendiente()
        tPendiente.Text = FormatCurrency(FormatNumber(tMontoTotal.Text) - FormatNumber(tMontoCliente.Text))
        If FormatNumber(tPendiente.Text) < 0 Then
            tPendiente.Text = FormatCurrency(0)
        End If

    End Sub

    Private Function CheckGarantiaCliente() As Boolean
        Dim retorno As Boolean = True
        For Each fila As DataGridViewRow In gVenta.Rows
            If fila.Cells("item").Value > 0 And fila.Cells("GARANTIACLIENTE").Value = Nothing Then
                Dim OK As Boolean = False
                For Each fil As DataGridViewRow In gVenta.Rows
                    If fil.Cells("GARANTIA").Value = ItemBL.GetGarantia(fila.Cells("item").Value) Then
                        OK = (True)
                    End If
                Next
                If Not OK Then retorno = False
            End If
        Next
        Return retorno
    End Function

    Private Function CheckPrecioVenta() As Boolean
        Dim retorno As Boolean = True
        For Each fila As DataGridViewRow In gVenta.Rows
            If fila.Cells("PRECIOVENTA").Value = 0 Then
                retorno = False
            End If
        Next
        Return retorno
    End Function

    Private Function GetGarantiaPendiente() As Long
        Dim gPendiente As Long = Nothing
        If gVenta.Rows.Count = 1 Then
            If oGPendiente.Checked Then
                For Each fila As DataGridViewRow In gVenta.Rows
                    gPendiente = fila.Cells("GARANTIACLIENTE").Value
                Next
            End If
        End If
        Return gPendiente
    End Function

    Private Sub cargarCliente()
        If Not IsNothing(_Cliente) Then
            tRut.Text = _Cliente.RUT
            tNumero.Text = _Cliente.NUMERO
            tNombre.Text = _Cliente.NOMBRE
            tFono.Text = _Cliente.FONO
            cVillas.SelectedValue = _Calle.VILLA
            lsCalles.SelectedValue = _Calle.CALLE
            lbClienteNuevo.Visible = False
        Else
            'tNumero.Clear()
            tRut.Clear()
            tNombre.Clear()
            tFono.Clear()
            lbClienteNuevo.Visible = True
        End If
    End Sub
#End Region

#Region "Métodos Públicos"

#End Region

#Region "Eventos Click"
    Private Sub gDisponibles_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gDisponibles.DoubleClick
        If gDisponibles.Rows.IndexOf(gDisponibles.CurrentRow) >= 0 Then
            Dim existe = False
            If gDisponibles.Item("STOCK", gDisponibles.Rows.IndexOf(gDisponibles.CurrentRow)).Value > 0 Then
                'For Each fila As DataGridViewRow In gVenta.Rows
                '    If fila.Cells("ITEM").Value = gDisponibles.Item("ITEM", gDisponibles.Rows.IndexOf(gDisponibles.CurrentRow)).Value Then
                '        'SI ES QUE EL ITEM YA ESTA AGREGADO A LA VENTA
                '        existe = True
                '    End If
                'Next
                'If existe Then
                '    For Each fila As DataGridViewRow In gVenta.Rows
                '        If fila.Cells("ITEM").Value = gDisponibles.Item("ITEM", gDisponibles.Rows.IndexOf(gDisponibles.CurrentRow)).Value Then
                '            fila.Cells("CANTIDAD").Value += 1
                '        End If
                '    Next
                'Else


                gVenta.Rows.Add(gDisponibles.Item("ITEM", gDisponibles.Rows.IndexOf(gDisponibles.CurrentRow)).Value,
                                0,
                                gDisponibles.Item("DESCRIPCION", gDisponibles.Rows.IndexOf(gDisponibles.CurrentRow)).Value,
                                gDisponibles.Item("PRECIOVENTA", gDisponibles.Rows.IndexOf(gDisponibles.CurrentRow)).Value
                                )
                Dim combo As New DataGridViewComboBoxColumn
                combo = DirectCast(gVenta.Columns("GARANTIACLIENTE"), DataGridViewComboBoxColumn)
                combo.DataSource = _GarantiasList
                combo.DisplayMember = "DESCRIPCION"
                combo.ValueMember = "GARANTIA"

                gDisponibles.Item("STOCK", gDisponibles.Rows.IndexOf(gDisponibles.CurrentRow)).Value -= 1
                'End If
            End If
        End If
    End Sub

    Private Sub gGarantias_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gGarantias.DoubleClick
        If gGarantias.Rows.IndexOf(gGarantias.CurrentRow) >= 0 Then
            Dim existe = False
            'If gGarantias.Item("STOCK", gGarantias.Rows.IndexOf(gGarantias.CurrentRow)).Value > 0 Then
            '    For Each fila As DataGridViewRow In gVenta.Rows
            '        If fila.Cells("GARANTIA").Value = gGarantias.Item("GARANTIA", gGarantias.Rows.IndexOf(gGarantias.CurrentRow)).Value Then
            '            existe = True
            '        End If
            '    Next
            'If existe Then
            '    For Each fila As DataGridViewRow In gVenta.Rows
            '        If fila.Cells("GARANTIA").Value = gGarantias.Item("GARANTIA", gGarantias.Rows.IndexOf(gGarantias.CurrentRow)).Value Then
            '            fila.Cells("CANTIDAD").Value += 1
            '            gGarantias.Item("STOCK", gGarantias.CurrentRow.Index).Value -= 1
            '        End If
            '    Next
            'Else
            'Dim combo As New DataGridViewComboBoxColumn
            'combo = DirectCast(gVenta.Columns("GARANTIACLIENTE"), DataGridViewComboBoxColumn)
            'combo.DataSource = Nothing
            gVenta.Rows.Add(0,
                             gGarantias.Item("GARANTIA", gGarantias.Rows.IndexOf(gGarantias.CurrentRow)).Value,
                       gGarantias.Item("DESCRIPCION", gGarantias.Rows.IndexOf(gGarantias.CurrentRow)).Value,
                        gGarantias.Item("PRECIOVENTA", gGarantias.Rows.IndexOf(gGarantias.CurrentRow)).Value
                      )

            gGarantias.Item("STOCK", gGarantias.Rows.IndexOf(gGarantias.CurrentRow)).Value -= 1
        End If
        'End If

        'End If
    End Sub

    Private Sub gVenta_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gVenta.Click
        If gVenta.Rows.IndexOf(gVenta.CurrentRow) >= 0 Then
            If gVenta.CurrentCell.OwningColumn.Name = "PRECIOVENTA" Then
                Using Precio As New IngresoDato("Ingreso de Precio", "Precio de Venta", "$")
                    Precio.ShowDialog()
                    If Precio.DialogResult = DialogResult.OK Then
                        gVenta.Item("PRECIOVENTA", gVenta.CurrentRow.Index).Value = Precio.GetValue
                        CalcularTotales()
                    End If
                End Using
            Else
                If gVenta.CurrentCell.OwningColumn.Name = "Quitar" Then

                    If gVenta.Item("GARANTIA", gVenta.CurrentRow.Index).Value <> 0 Then
                        For Each row As DataGridViewRow In gGarantias.Rows
                            If gGarantias.Item("GARANTIA", row.Index).Value = gVenta.Item("GARANTIA", gVenta.CurrentRow.Index).Value Then
                                gGarantias.Item("STOCK", row.Index).Value += 1
                            End If
                        Next
                    End If

                    If gVenta.Item("ITEM", gVenta.CurrentRow.Index).Value <> 0 Then
                        For Each row As DataGridViewRow In gDisponibles.Rows
                            If gDisponibles.Item("ITEM", row.Index).Value = gVenta.Item("ITEM", gVenta.CurrentRow.Index).Value Then
                                gDisponibles.Item("STOCK", row.Index).Value += 1

                            End If
                        Next
                    End If

                    gVenta.Rows.Remove(gVenta.CurrentRow)
                    CalcularTotales()
                End If
            End If
        End If
    End Sub

    Private Sub bCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCancelar.Click
        Me.Dispose()
    End Sub

    Private Sub bRealizarVenta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bRealizarVenta.Click
        If Not IsNumeric(cVillas.SelectedValue) And cVillas.SelectedValue < 1 Then
            Util.Mensaje("Debe Seleccionar Villa")
            cVillas.Focus()
            Exit Sub
        End If
        If Not IsNumeric(lsCalles.SelectedValue) And lsCalles.SelectedValue < 1 Then
            Util.Mensaje("Debe Seleccionar Calle")
            lsCalles.Focus()
            Exit Sub
        End If
        If tNumero.TextLength = 0 Then
            Util.Mensaje("Debe Ingresar Número")
            tNumero.Focus()
            Exit Sub
        End If
        If tRut.Text <> "  .   .   -" Then
            If Not Util.ValidaRut(tRut.Text) Then
                Util.Mensaje("El Rut Ingresado no es Correcto")
                tRut.Focus()
                Exit Sub
            End If
        End If
        If gVenta.Rows.Count = 0 Then
            Util.Mensaje("Debe Agregar Productos a la Venta")
            gDisponibles.Focus()
            Exit Sub
        End If

        If Not IsNumeric(cFormaPago.SelectedValue) And cFormaPago.SelectedIndex < 0 Then
            Util.Mensaje("Debe Seleccionar Forma de Pago")
            cFormaPago.Focus()
            Exit Sub
        End If
        If (CLng(tMontoCliente.Text)) < 0 Then
            Util.Mensaje("Ajuste Correctamente el Monto del Cliente")
            tMontoCliente.Focus()
            Exit Sub
        End If
        If Not CheckPrecioVenta() Then
            Util.Mensaje("Debe Asignar Precio(s) de Venta(s)")
            gVenta.Focus()
            Exit Sub
        End If
        If Not CheckGarantiaCliente() Then
            Util.Mensaje("Debe Seleccionar la Garantia del Cliente")
            gVenta.Focus()
            Exit Sub
        End If
        If (CLng(tPendiente.Text)) > 0 Then
            If Util.Pregunta("¿Desea Dejar Pendiente el Pago de la Venta Actual?") Then
                If tFechaPago.Value.ToShortDateString.Equals(Now.ToShortDateString) Then
                    Util.Mensaje("Seleccione Fecha de Pago distinta a la de hoy")
                    tFechaPago.Focus()
                    Exit Sub
                End If
            Else
                Exit Sub
            End If
        End If
        If oGPendiente.Checked Then
            If tFechaDevolucion.Value.ToShortDateString.Equals(Now.ToShortDateString) Then
                Util.Mensaje("Seleccione Fecha de Devolución distinta a la de hoy")
                tFechaDevolucion.Focus()
                Exit Sub
            End If
        End If
        If Not IsNumeric(cCamion.SelectedValue) And Not cCamion.SelectedIndex > -1 Then
            Util.Mensaje("Debe Seleccionar Camión")
            cCamion.Focus()
            Exit Sub
        End If
        If Not IsNumeric(cChofer.SelectedValue) And Not cChofer.SelectedIndex > -1 Then
            Util.Mensaje("Debe Seleccionar Chofer")
            cChofer.Focus()
            Exit Sub
        End If
        If oPedidoPOS.Checked Then
            If tNPedido.TextLength = 0 Then
                Util.Mensaje("Debe Ingresar el úmero de Pedido de POS")
                tNPedido.Focus()
                Exit Sub
            End If
            If CLng((tDesctoPOS.Text)) = 0 Then
                Util.Mensaje("Debe Ingresar el Valor del Descuento")
                tDesctoPOS.Focus()
                Exit Sub
            End If
        End If
       
        ''''''''''''BOLETA 
        Dim boleta As New boletas

        With boleta
            .FECHA = Now
            .DESCRIPCION = xComentarios.Text.Trim.ToUpper
            .TOTAL = FormatNumber(tMontoTotal.Text)
            .MONTONETO = FormatNumber(tSubTotal.Text)
            .DESCUENTO = FormatNumber(tDescto.Text) + FormatNumber(tDesctoPOS.Text)
        End With
        boleta = BoletaBL.Save(boleta)
        If IsNothing(boleta) Then
            Util.MensajeError("Error al Realizar Venta")
            Exit Sub
        End If

        Dim garantiaPrestada As Long = GetGarantiaPendiente()

        If IsNothing(_Cliente) Then _Cliente = New clientes
        With _Cliente
            .NUMERO = tNumero.Text.Trim.ToUpper
            .CALLE = lsCalles.SelectedValue
            .RUT = tRut.Text
            .NOMBRE = tNombre.Text.Trim.ToUpper
            .FONO = tFono.Text.Trim.ToUpper

            If Not IsNothing(garantiaPrestada) Then .FECHADEVOLUCION = tFechaDevolucion.Value Else .FECHADEVOLUCION = Nothing
            .ACTIVO = True
        End With
        ClienteBL.Save(_Cliente)

        ''''''''''''VENTA'''''''''
        Dim venta As New ventas
        With venta
            .DISTRIBUIDOR = 0
            .BOLETA = boleta.BOLETA
            .FACTURAID = 0
            .RUT = cChofer.SelectedValue
            .PATENTE = cCamion.SelectedValue
            .CLIENTE = _Cliente.CLIENTE
            .KILOS = Val(tKilos.Text)
            .PRECIOTOTAL = CLng(FormatNumber(tMontoTotal.Text))
            .SUBTOTAL = CLng(FormatNumber(tSubTotal.Text))
            .FECHA = tFechaVenta.Value

            .PENDIENTE = CLng(tPendiente.Text)
            If .PENDIENTE > 0 Then .FECHAPAGO = tFechaPago.Value Else .FECHAPAGO = Nothing
            If oPedidoPOS.Checked Then .DESCTOPOS = CLng((tDesctoPOS.Text)) Else .DESCTOPOS = 0
            If CLng(tDescto.Text) > 0 Then .DESCTO = CLng(tDescto.Text) Else .DESCTO = 0
            If garantiaPrestada = 0 Then .GARANTIA = 0 Else .GARANTIA = garantiaPrestada
            If oPedidoPOS.Checked Then .PEDIDOPOSID = CLng(Val(tNPedido.Text)) Else .PEDIDOPOSID = 0

            .DEVUELTO = False
        End With


        '''''''''''DETALLEVENTA''''''''''''
        Dim detalles As New List(Of detalleventa)
        Dim GarantiaCambiada As New garantiascambiadas
        For Each fila As DataGridViewRow In gVenta.Rows
            Dim det As New detalleventa
            With det
                .VENTA = venta.VENTA
                .ITEM = CInt(fila.Cells("ITEM").Value)
                .GARANTIA = CInt(fila.Cells("GARANTIA").Value)
                .CANTIDAD = 1
                .PRECIOVENTA = CInt(fila.Cells("PRECIOVENTA").Value)
            End With
            detalles.Add(det)

            '''''''''''ACTUALIZAR STOCK Y PRECIO VENTA''''''''''''

            _Item_ = ItemBL.SearchById(det.ITEM)

            'EN CASO QUE LA GARANTIA DEL CLIENTE SEA DISTINTA A LA DEL ITEM DE VENTA
            If Not IsNothing(fila.Cells("GARANTIACLIENTE").Value) AndAlso fila.Cells("GARANTIACLIENTE").Value <> _Item_.GARANTIA Then
                If Not oGPendiente.Checked Then
                    'AGREGA AL STOCK LA GARANTIA DE CLIENTE
                    GarantiaBL.UpdateStock(fila.Cells("GARANTIACLIENTE").Value, -1)
                    'DESCUENTA EL STOCK DE LA GARANTIA DEL ITEM VENDIDO
                    GarantiaBL.UpdateStock(_Item_.GARANTIA, 1)
                    'grabar la garantia que se debe devolver al cliente
                    GarantiaCambiada.GARANTIACAMBIADAID = CLng(fila.Cells("GARANTIACLIENTE").Value)
                    GarantiaCambiada.GARANTIAVENTAID = _Item_.GARANTIA
                End If
            End If
        Next
        venta = VentaBL.Save(venta, detalles, oGPendiente.Checked, GarantiaCambiada)

        If venta.PENDIENTE <> venta.PRECIOTOTAL Then
            ''''''''''''PAGO'''''''''''
            Dim pago As New pagos
            With pago
                .TIPO = Util.TipoPago.Boleta
                .MONTO = CLng(FormatNumber(tMontoCliente.Text))
                .FORMAPAGO = cFormaPago.SelectedValue
                .FECHA = Now
            End With
            pago = PagosBL.Save(pago)
            If IsNothing(pago) Then
                Util.MensajeError("Error al Realizar Venta")
                Exit Sub
            End If
            ''''''''''''BOLETASPAGOS''''''''''
            Dim bolpago As New pagosventa
            bolpago.VENTA = venta.VENTA
            bolpago.PAGO = pago.PAGO
            VentaBL.SavePagosVenta(bolpago)
            If IsNothing(bolpago) Then
                Util.MensajeError("Error al Realizar Venta")
                Exit Sub
            End If
        End If
        If Not IsNothing(venta) Then
            Util.Mensaje("Venta Realizada Exitosamente")
            Limpiar()
            CargarListas()
        Else
            Util.MensajeError("Error al Realizar Venta")
        End If
    End Sub

    Private Sub bNuevaCalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bNuevaCalle.Click
        Using ManCalles As New MantencionCalles(cVillas.SelectedValue)
            ManCalles.ShowDialog()
        End Using
    End Sub

#End Region

#Region "Eventos Change"
    'Private Sub gpVenta_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gpVenta.VisibleChanged
    '    lbTotal.Text = CalcularTotal()
    'End Sub

    Private Sub xCalle_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tCalle.TextChanged
        If tCalle.TextLength > 0 Then
            lsCalles.SelectedIndex = lsCalles.FindString(tCalle.Text.Trim)
        End If
    End Sub



    Private Sub xNumero_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tNumero.TextChanged
        'If xNumero.TextLength > 0 And Not IsNothing(_ClientesList) Then
        '    Debug.Print("antes _ClientesList.Count: " + _ClientesList.Count.ToString)

        '    Dim autoComplete As New AutoCompleteStringCollection
        '    Dim clientesList As New List(Of Entities.CLIENTES)

        '    clientesList = _ClientesList.Where(Function(c) c.NUMERO.Contains(xNumero.Text.Trim)).ToList

        '    Debug.Print("despues _ClientesList.Count: " + clientesList.Count.ToString)

        '    For Each cli As Entities.CLIENTES In _ClientesList
        '        autoComplete.Add(cli.NUMERO)
        '    Next
        '    xNumero.AutoCompleteMode = AutoCompleteMode.Suggest
        '    xNumero.AutoCompleteSource = AutoCompleteSource.CustomSource
        '    xNumero.AutoCompleteCustomSource = autoComplete
        'End If

        'Dim autocompleta As New AutoCompleteStringCollection

        '_ClientesList = ClienteBL.ListByCalleId(_Calle.CALLE)
        'For Each cli As Entities.CLIENTES In _ClientesList
        '    autocompleta.Add(cli.NUMERO)
        'Next
        'xNumero.AutoCompleteMode = AutoCompleteMode.Suggest
        'xNumero.AutoCompleteSource = AutoCompleteSource.CustomSource
        'xNumero.AutoCompleteCustomSource = autocompleta


        'If _ClientesList.Count = 1 Then
        '    _Cliente = _ClientesList.Where(Function(c) c.NUMERO.Contains(xNumero.Text.Trim)).Single
        '    If Not IsNothing(_Cliente) Then
        '        xRut.Text = _Cliente.RUT
        '        xNombre.Text = _Cliente.NOMBRE
        '        xFono.Text = _Cliente.FONO
        '    End If
        'Else

        'End If

    End Sub

    Private Sub cVillas_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cVillas.SelectedIndexChanged
        If IsNumeric(cVillas.SelectedValue) AndAlso cVillas.SelectedValue > 0 Then
            _CallesList = CalleBL.ListByVillaId(CLng(cVillas.SelectedValue))
            TituloCalle()

        End If
    End Sub

    Private Sub lsCalles_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lsCalles.SelectedIndexChanged
        If lsCalles.SelectedIndex > -1 And IsNumeric(lsCalles.SelectedValue) Then
            _ClientesList = ClienteBL.ListByCalleId(lsCalles.SelectedValue)
            _Calle = _CallesList.Where(Function(p) p.CALLE.Equals(lsCalles.SelectedValue)).SingleOrDefault
            tCalle.Text = _Calle.NOMBRE
            Debug.Print("lsCalles_SelectedIndexChanged _ClientesList.Count = " & _ClientesList.Count)
        End If
    End Sub
#End Region

    Private Sub xNumero_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles tNumero.Leave
        If tNumero.TextLength > 0 Then
            _Cliente = ClienteBL.SearchByDireccion(tNumero.Text.Trim, lsCalles.SelectedValue)
            cargarCliente()
        End If
    End Sub

    Private Sub gVenta_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles gVenta.RowsAdded

        If gVenta.Rows.Count > 0 Then
            tMontoCliente.Text = FormatCurrency(CLng(Val(tMontoCliente.Text)) + CLng(Val(gVenta.Item("PRECIOVENTA", e.RowIndex).Value)))
        End If
        If gVenta.Item("GARANTIA", e.RowIndex).Value > 0 Then
            Dim cell As DataGridViewComboBoxCell = DirectCast(gVenta.Rows(e.RowIndex).Cells("GARANTIACLIENTE"), DataGridViewComboBoxCell)
            cell.DataSource = Nothing
        End If
        If gVenta.Rows.Count = 1 Then
            If gVenta.Item("ITEM", e.RowIndex).Value > 0 Then
                oGPendiente.Enabled = True
            End If
        Else
            oGPendiente.Checked = False
            oGPendiente.Enabled = False
        End If
        AjustarColumnas()
        CalcularTotales()
    End Sub

    Private Sub gVenta_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles gVenta.RowsRemoved
        'If gVenta.Rows.Count > 0 Then
        '    tMontoCliente.Text = FormatCurrency(CLng(Val(tMontoCliente.Text)) - CLng(Val(gVenta.Item("PRECIOVENTA", e.RowIndex).Value)))
        'End If
        If gVenta.Rows.Count = 1 Then
            If gVenta.Item("ITEM", 0).Value > 0 Then
                oGPendiente.Enabled = True
            End If
        End If
        AjustarColumnas()
        CalcularTotales()
    End Sub

    Private Sub tMontoCliente_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tMontoCliente.Leave
        Try
            tMontoCliente.Text = FormatCurrency(tMontoCliente.Text)
            Dim n = CLng(FormatNumber(tMontoCliente.Text))
            CalcularTotales()
        Catch ex As Exception
            tMontoCliente.Text = FormatCurrency(0)
        End Try
        
    End Sub

    Private Sub tDescto_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles tDesctoPOS.Leave
        Try
            tDesctoPOS.Text = FormatCurrency(tDesctoPOS.Text)
            Dim n = CLng(FormatNumber(tDesctoPOS.Text))
            CalcularTotales()
        Catch ex As Exception
            tDesctoPOS.Text = FormatCurrency(0)
        End Try
       
    End Sub

    Private Sub oGPendiente_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles oGPendiente.CheckedChanged
        If oGPendiente.Checked Then
            lbFechaDevolucion.Visible = True
            tFechaDevolucion.Visible = True
        Else
            lbFechaDevolucion.Visible = False
            tFechaDevolucion.Visible = False
        End If
    End Sub

    Private Sub tPedidoPOS_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles oPedidoPOS.CheckedChanged
        If oPedidoPOS.Checked Then
            tNPedido.Visible = True
            lbNPedido.Visible = True
            tDesctoPOS.Visible = True
            lbValor.Visible = True
        Else
            tNPedido.Visible = False
            lbNPedido.Visible = False
            tDesctoPOS.Visible = False
            lbValor.Visible = False
        End If
    End Sub

    Private Sub tPendiente_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tPendiente.TextChanged
        If CLng(tPendiente.Text) > 0 Then
            lbFechaPago.Visible = True
            tFechaPago.Visible = True
        Else
            lbFechaPago.Visible = False
            tFechaPago.Visible = False
        End If
    End Sub

#Region "Eventos Keypress"
    Private Sub tDesctoPOS_KeyPress(sender As Object, e As KeyPressEventArgs) Handles tDesctoPOS.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub
    Private Sub cVillas_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cVillas.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub RealizarVenta_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tCalle_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tCalle.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tNumero_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tNumero.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tRut_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tRut.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tNombre_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tNombre.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tFono_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tFono.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub lsCalles_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles lsCalles.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tFechaDevolucion_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tFechaDevolucion.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tKilos_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tKilos.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tMontoTotal_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tMontoTotal.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub cFormaPago_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cFormaPago.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub


    Private Sub tMontoCliente_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tMontoCliente.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tPendiente_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tPendiente.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub tFechaPago_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tFechaPago.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub cCamion_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cCamion.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub cChofer_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cChofer.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub xComentarios_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles xComentarios.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub
    Private Sub xComentarios_KeyPress1(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tDescto.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub
    Private Sub oGPendiente_KeyPress(sender As Object, e As KeyPressEventArgs) Handles oGPendiente.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub oPedidoPOS_KeyPress(sender As Object, e As KeyPressEventArgs) Handles oPedidoPOS.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub oBoleta_KeyPress(sender As Object, e As KeyPressEventArgs)
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub

    Private Sub oFactura_KeyPress(sender As Object, e As KeyPressEventArgs)
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub
    Private Sub tNPedido_KeyPress(sender As Object, e As KeyPressEventArgs) Handles tNPedido.KeyPress
        If e.KeyChar = ChrW(Keys.Enter) Then
            Util.Siguiente()
        End If
    End Sub
#End Region

    Private Sub cFormaPago_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cFormaPago.SelectedIndexChanged
        CalcularTotales()
    End Sub

    Private Sub tDescto_Leave1(sender As Object, e As EventArgs) Handles tDescto.Leave
        Try
            tDescto.Text = FormatCurrency(tDescto.Text)
            Dim n = CLng(FormatNumber(tDescto.Text))
            CalcularTotales()
        Catch ex As Exception
            tDescto.Text = FormatCurrency(0)
        End Try
      
    End Sub

    Private Sub tMontoCliente_Enter(sender As Object, e As EventArgs) Handles tMontoCliente.Click
        If (Not String.IsNullOrEmpty(tMontoCliente.Text)) Then
            tMontoCliente.SelectionStart = 0
            tMontoCliente.SelectionLength = tMontoCliente.Text.Length
        End If
    End Sub

    Private Sub tDesctoPOS_Enter(sender As Object, e As EventArgs) Handles tDesctoPOS.Click
        If (Not String.IsNullOrEmpty(tDesctoPOS.Text)) Then
            tDesctoPOS.SelectionStart = 0
            tDesctoPOS.SelectionLength = tDesctoPOS.Text.Length
        End If
    End Sub

    Private Sub tDescto_Click(sender As Object, e As EventArgs) Handles tDescto.Click
        If (Not String.IsNullOrEmpty(tDescto.Text)) Then
            tDescto.SelectionStart = 0
            tDescto.SelectionLength = tDescto.Text.Length
        End If
    End Sub

    Private Sub tDesctoPOS_TextChanged(sender As Object, e As EventArgs) Handles tDesctoPOS.TextChanged

    End Sub

    Private Sub lbNPedido_Click(sender As Object, e As EventArgs) Handles lbNPedido.Click

    End Sub

    Private Sub tNPedido_TextChanged(sender As Object, e As EventArgs) Handles tNPedido.TextChanged

    End Sub

    Private Sub lbValor_Click(sender As Object, e As EventArgs) Handles lbValor.Click

    End Sub
End Class